package com.example.localvideoplayer.adapter

import android.content.ContentUris
import android.content.Context
import android.content.Intent
import android.provider.MediaStore
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.localvideoplayer.LocalVideoInfo
import com.example.localvideoplayer.PlayActivity
import com.example.localvideoplayer.R


class LocalVideoAdapter(private val context: Context, private val mDatas: List<LocalVideoInfo>) :
    RecyclerView.Adapter<LocalVideoAdapter.LocalViewHolder>() {
    var currentPos: Int? = null


    inner class LocalViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
//        val mSurfaceView = itemView.findViewById<SurfaceView>(R.id.item_surface)
        var mThumblv: ImageView = itemView.findViewById(R.id.item_iv)
//        var mTitleTv: TextView = itemView.findViewById<TextView>(R.id.item_tv_title)
//        var mDurationTv: TextView = itemView.findViewById<TextView>(R.id.item_tv_time)
//        var mSizeTv: TextView = itemView.findViewById<TextView>(R.id.item_tv_size)

    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): LocalViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.local_video_item, parent, false)

        return LocalViewHolder(view)
    }

    override fun onBindViewHolder(holder: LocalViewHolder, position: Int) {
        val video = mDatas[position]
//        holder.mTitleTv.text = video.name
//        val sdf = SimpleDateFormat("mm:ss")
//        val time = sdf.format(Date(video.duration.toLong()))
//        holder.mDurationTv.text = time
//        val mSize = video.size / 1024 / 1024
//        holder.mSizeTv.text = "视频大小；$mSize M"

        val id = ContentUris.parseId(video.uri)
        val resolver = context.contentResolver
        val thumbnail = MediaStore.Video.Thumbnails.getThumbnail(
            resolver,
            id,
            MediaStore.Video.Thumbnails.MINI_KIND,
            null
        )

        holder.mThumblv.setImageBitmap(thumbnail)
        holder.mThumblv.tag = position
        holder.mThumblv.setOnClickListener {
            val pos = it.tag
            currentPos = pos as Int
//            Toast.makeText(context, "click video item", Toast.LENGTH_SHORT).show



            val intent = Intent(context, PlayActivity::class.java).apply {
                this.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                this.putExtra("uri", video.uri.toString())
            }
            context.startActivity(intent)

        }


    }

    override fun getItemCount() = mDatas.size
}